package com.icloud.cer.rest.msg.processor;

import java.net.InetSocketAddress;

import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.icloud.cer.rest.Constants;
import com.icloud.cer.rest.msg.MessageHeader;
import com.icloud.cer.rest.msg.MessageHolder;
import com.icloud.cer.rest.msg.MsgConstants;
import com.icloud.cer.rest.msg.bean.EncryptRequest;
import com.icloud.cer.rest.util.MessageSequenceGenerator;
import com.icloud.cer.rest.util.SenderManager.TimeoutMessage;

public class Msg100Processor extends BaseMessageProcessor implements MessageProcessor {
	private final Logger log = LoggerFactory.getLogger(Msg100Processor.class);
	
	@Override
	public void process(IoSession session, MessageHolder holder) {
		long sessionId = session.getId();
		InetSocketAddress clientAddr = connectorManager.getClientAddr(sessionId);
		if(clientAddr == null) {
			log.error("客户端没有注册，请重新注册");
			return;
		}
		//从任务池中取任务
		TimeoutMessage timeoutMessage = senderManager.getTask();
		if(timeoutMessage == null) {
			log.warn("No task to send.");
//			log.warn("mock 1 task");//mock 一个任务
//			MessageHolder sendHolder = mockTask();
//			session.write(sendHolder);
			return;
		}
		MessageHolder sendHolder = timeoutMessage.getMessage();
		session.write(sendHolder);
		
	}
	
	private MessageHolder mockTask() {
		MessageHolder mh = new MessageHolder(MsgConstants.SERVER_SENT_ENCRYPT);
		MessageHeader head = new MessageHeader();
		head.setSize_(EncryptRequest.BYTE_COUNT);
		head.setFlag_(Constants.DEFAULT_CODEC_FLAG);
		head.setType_(MsgConstants.SERVER_SENT_ENCRYPT);
		
		EncryptRequest request = new EncryptRequest();
		long seq = MessageSequenceGenerator.getNextMessageId();
		log.info("seq:" + seq);
		request.setSequence(seq);
		request.setTaskId(1l);
		request.setUserId("hellohellohellohellohellohello12");
		request.setCertification(getCer());
		
		mh.setHead(head);
		mh.setValue(request);
		return mh;
	}

	private String getCer() {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < 16; i++) {
			sb.append("2014011020140110");
		}
		return sb.toString();
	}

}
